package com.order.manager.controller.User;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.order.manager.Model.UserAddress;
import com.order.manager.Model.other.Options;
import com.order.manager.Model.other.RestBean;
import com.order.manager.service.impl.UserAddressServiceImpl;
import com.order.manager.util.JwtUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RequestMapping("/api/userAddress")
@RestController
public class UserAddressController {

    @Resource
    UserAddressServiceImpl userAddressService;

    @Resource
    JwtUtil jwtUtil;



    @RequestMapping("/select")
    public RestBean getAddressByUser(HttpServletRequest request){
        String uuid = jwtUtil.getJwtUsername(request);
        List<UserAddress> userAddresses = userAddressService.list(new QueryWrapper<UserAddress>()
                .eq("user_id", uuid)
        );
        return RestBean.success(userAddresses);
    }

    @RequestMapping("/select/option")
    public RestBean getAddressOptionByUser(HttpServletRequest request){
        String uuid = jwtUtil.getJwtUsername(request);
        List<UserAddress> userAddresses = userAddressService.list(new QueryWrapper<UserAddress>()
                .eq("user_id", uuid)
        );
        List<Options> options=new ArrayList<>();
        userAddresses.forEach(el->{
            Options option=new Options(el.getAddress(),el.getAddressId().toString());
            options.add(option);
        });
        return RestBean.success(options);
    }

    @RequestMapping("/del/{id}")
    public RestBean delAddressById(@PathVariable Long id){
        return userAddressService.removeById(id)?RestBean.success():
                RestBean.failure(500,"删除失败");
    }

    @RequestMapping("/insert")
    public RestBean insert(HttpServletRequest request,String address){
        UserAddress userAddress=new UserAddress();
        userAddress.setUserId(jwtUtil.getJwtUsername(request));
        userAddress.setAddress(address);
        return userAddressService.save(userAddress)?RestBean.success():RestBean.failure(500,"新增失败");
    }
}
